<template>
    <div class="perm-page">
        <!-- 标题 -->
        <div class="page-header">
            <h2>权限管理</h2>
        </div>

        <!-- 查询表单 -->
        <el-card class="search-card">
            <el-form :model="query" inline @keyup.enter.native="handleSearch">
                <el-form-item label="权限名称">
                    <el-input v-model="query.PermissionName" placeholder="按权限名称模糊查询" clearable style="width: 240px" />
                   
                </el-form-item>
               
                <el-form-item>
                    <el-button type="primary" :loading="loading" @click="handleSearch"><el-icon><Search /></el-icon>查询</el-button>
                    <el-button type="primary" @click="openCreate"><el-icon><Plus /></el-icon>新增权限</el-button>
                    <el-button @click="handleReset"><el-icon><Refresh /> </el-icon> 重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 表格 -->
        <el-card class="table-card">
            <div class="table-header">
                <h3>权限列表</h3>
                <span class="total">共 {{ total }} 条</span>
            </div>

            <el-table :data="tableData" v-loading="loading" stripe border style="width: 100%">
                <el-table-column prop="PermissionsId" label="序号" width="100" />
                <el-table-column prop="PermissionName" label="权限名称" min-width="160" />
                <el-table-column prop="Component" label="URL" min-width="180" show-overflow-tooltip />
                <el-table-column prop="CreateTime" label="创建时间" width="200">
                    <template #default="{ row }">{{ formatDate(row.CreateTime) }}</template>
                </el-table-column>
            </el-table>

            <div class="pagination">
                <el-pagination v-model:current-page="pageIndex" v-model:page-size="pageSize" :total="total"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 新增权限弹窗 -->
        <el-dialog v-model="dialogVisible" title="新增权限" width="520px" :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="96px">
                <el-form-item label="权限名称" prop="PermissionName">
                    <el-input v-model="form.PermissionName" maxlength="50" show-word-limit placeholder="请输入权限名称" />
                </el-form-item>
                <el-form-item label="组件路径" prop="Component">
                    <el-input v-model="form.Component" placeholder="如：/system/permission" />
                </el-form-item>
                <el-form-item label="上级权限">
                    <el-cascader v-model="cascaderValue" :options="cascaderOptions"
                        :props="{ checkStrictly: true, emitPath: true, value: 'value', label: 'label', children: 'children' }"
                        clearable placeholder="不选择则为顶层" style="width: 100%" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { getPermissions, type PermissionItem, getPermissionTree, createPermission, type PermissionTreeNode } from '@/api/role'

// 查询与分页参数
const query = reactive({
    PermissionName: ''
})
const pageIndex = ref(1)
const pageSize = ref(10)

// 数据状态
const loading = ref(false)
const tableData = ref<PermissionItem[]>([])
const total = ref(0)

const formatDate = (d?: string) => (d ? new Date(d).toLocaleString('zh-CN') : '')

const fetchData = async () => {
    loading.value = true
    try {
        const res = await getPermissions({
            PermissionName: query.PermissionName?.trim() || undefined,
            PageIndex: pageIndex.value,
            PageSize: pageSize.value
        })
        if (res.code === 200) {
            tableData.value = res.PageData || []
            total.value = res.TotalCount || 0
        } else {
            ElMessage.error(res.msg || '获取权限数据失败')
        }
    } catch (e) {
        console.error(e)
        ElMessage.error('获取权限数据失败')
    } finally {
        loading.value = false
    }
}

const handleSearch = () => {
    pageIndex.value = 1
    fetchData()
}

const handleReset = () => {
    query.PermissionName = ''
    pageIndex.value = 1
    pageSize.value = 10
    fetchData()
}

const handleSizeChange = (size: number) => {
    pageSize.value = size
    pageIndex.value = 1
    fetchData()
}

const handleCurrentChange = (page: number) => {
    pageIndex.value = page
    fetchData()
}

onMounted(fetchData)

// ========== 新增权限 ==========
const dialogVisible = ref(false)
const submitLoading = ref(false)
const formRef = ref()
const form = reactive({
    PermissionName: '',
    Component: '',
})
const rules = {
    PermissionName: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
    Component: [{ required: true, message: '请输入组件路径', trigger: 'blur' }],
}

// 级联数据
const cascaderOptions = ref<any[]>([])
const cascaderValue = ref<number[] | undefined>()

const transformTree = (nodes: PermissionTreeNode[]): any[] => {
    return nodes.map(n => ({
        value: n.PermissionsId,
        label: n.PermissionName,
        children: n.Children && n.Children.length ? transformTree(n.Children) : undefined,
    }))
}

const loadCascader = async () => {
    try {
        const res = await getPermissionTree()
        if (res.code === 200) {
            const tree = transformTree(res.data || [])
            cascaderOptions.value = [
                { value: 0, label: '顶层（无上级）' },
                ...tree,
            ]
        }
    } catch (e) {
        console.error(e)
    }
}

const openCreate = async () => {
    form.PermissionName = ''
    form.Component = ''
    cascaderValue.value = undefined
    await loadCascader()
    dialogVisible.value = true
}

const handleSubmit = () => {
    (formRef.value as any).validate(async (valid: boolean) => {
        if (!valid) return
        submitLoading.value = true
        try {
            const superior = Array.isArray(cascaderValue.value) && cascaderValue.value.length > 0
                ? cascaderValue.value[cascaderValue.value.length - 1]
                : 0
            const res = await createPermission({
                PermissionName: form.PermissionName,
                Component: form.Component,
                Superior: Number(superior) || 0,
            })
            if (res.code === 200) {
                ElMessage.success(res.msg || '新增成功')
                dialogVisible.value = false
                // 刷新列表
                fetchData()
            } else {
                ElMessage.error(res.msg || '新增失败')
            }
        } catch (e) {
            console.error(e)
            ElMessage.error('新增失败')
        } finally {
            submitLoading.value = false
        }
    })
}
</script>

<style scoped>
.perm-page {
    padding: 12px;
}

.page-header {
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.page-header h2 {
    margin: 0 0 4px;
}

.search-card {
    margin-bottom: 12px;
}

.table-card {
    margin-top: 0;
}

.table-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
}

.table-header .total {
    color: #909399;
    font-size: 13px;
}

.pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 12px;
}
</style>